package com.group.three.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class JedisConfig {
    @Value(value = "${spring.redis.jedis.pool.max-idle}")
    private Integer maxIdle;
    @Value(value = "${spring.redis.jedis.pool.min-idle}")
    private Integer minIdle;
    @Value(value = "${spring.redis.jedis.pool.max-active}")
    private Integer maxActive;
    @Value(value = "${spring.redis.password}")
    private String password;
    @Value(value = "${spring.redis.host}")
    private String host;
    @Value(value = "${spring.redis.port}")
    private Integer port;
    @Value(value = "${spring.redis.timeout}")
    private Integer timeout;

    //创建redis连接池
    @Bean
    public ShardedJedisPool shardedJedisPool(){
        //redis链接池参数对象
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxTotal(maxActive);
        //集群类型redis数据库链接配置,每个对象代表一个redis数据库
        List<JedisShardInfo> jedisShardInfoList = new ArrayList<>();
        JedisShardInfo info = new JedisShardInfo(host, port, timeout);
        info.setPassword(password);
        //将元素加入list中
        jedisShardInfoList.add(info);
        ShardedJedisPool shardedJedisPool = new ShardedJedisPool(config, jedisShardInfoList);
        log.info("redis连接池链接成功");
        return shardedJedisPool;
    }
}
